package com.audaque.springboot.foshanupload.web.util;

import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.core.properties.SwitchProperties;
import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.web.exception.RException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

@Slf4j
public class ExceptionHandlerUtils {

    public static Object commonErrorHandler(Throwable e, ResultCodeEnum en, String code, String msg, SwitchProperties switchProperties) throws Throwable {
        if (e.getStackTrace() != null && e.getStackTrace().length > 0) {
            //得到异常栈的首个元素
            StackTraceElement stackTraceElement = e.getStackTrace()[0];
            //异常类全路径
            log.error("path: " + stackTraceElement.getClassName());
            //异常行数
            log.error("line: " + stackTraceElement.getLineNumber());
        }
        //异常信息
        log.error("error: " + e.toString());
        log.error("en: " + en);
        log.error("code: " + code);
        log.error("msg: " + msg);
        log.error("stackTrace: " + JSONUtil.toJsonStr(e.getStackTrace()));
        e.printStackTrace();
        StringBuffer stringBuffer = new StringBuffer();
        String message = null;


        // 服务端错误
        if (en != null) {
            code = en.getCode();
        } else if (e instanceof RException) {
            code = ((RException) e).getErrcode();
        } else {
            code = ResultCodeEnum.FAILE.getCode();
        }


        if (en != null) {
            stringBuffer.append(" : ").append(en.getMsg());
        }
        if (e instanceof RException) {
            stringBuffer.append(" : ").append(e.getMessage());
        } else {
            if (StringUtils.isNotBlank(msg)) {
                stringBuffer.append(" : ").append(msg);
            } else {
                if (switchProperties.getDebug()) {
                    stringBuffer.append(" : ").append(ExceptionUtils.getMessage(e));
                } else {
                    stringBuffer.append(" : ").append(ResultCodeEnum.FAILE.getMsg());
                }
            }

        }
        message = stringBuffer.toString();
        log.error("message: " + message);

        R<Object> r = new R<>();
        r.setCode(code);
        r.setMsg(message);
        r.setSuccess(false);

        if (switchProperties.getReturnR()) {
            return r;
        } else {
            return message;
        }
    }

}
